<?php
/**
 * Access layer manager
 * Applications can send request for authentication.
 * @package Account
 * @author Urban Soban
 * @copyright 2009 Urban Soban
 */
class Access {
	/**
	 * Holds account instance
	 * @var Account
	 */
	private $Account;

	/**
	 * Array with application names to which user with given access layer cannot access
	 * @var array
	 */
	private $CannotAccess = array();

	/**
	 * MySQL instance
	 * @var MySQL
	 */
	private $MySQL;

	/**
	 * Creates new Access object
	 * @param Account $Account
	 * @param MysqlHelper $MySQL
	 */
	function __construct(Account $Account, MysqlHelper $MySQL){
		$this->Account = $Account;
		$this->MySQL = $MySQL;

		$this->populateAccessList();
	}

	/**
	 * Populates {Access::$CannotAccess} with application names
	 */
	function populateAccessList(){
		$SelectQuery = $this->MySQL->query("SELECT * FROM {$this->MySQL->getPrefix()}access WHERE id = {$this->Account->getAccess()}");
		$apps = mysql_fetch_assoc($SelectQuery);

			if($apps["applications"] == "*"){
				return;
			}

		$explode = explode(";", $apps["applications"]);

		foreach ($explode as $app){
			if(is_dir(dirname(__FILE__)."/../".$app)){
				$this->CannotAccess[] = $app;
			}
		}
	}

	/**
	 * Checks if user is authenticated to use the application
	 *
	 * @param string $app_name
	 * @return boolean true on success, false on failure
	 */
	function canAccess($app_name){
		if(in_array($app_name, $this->CannotAccess)){
			return false;
		}

		return true;
	}

	/**
	 * Updates or creates access layer. Accepts array of application names to which user cannot access, layer id and layer name.
	 * If layer is to be created, layer name has to be given, but layer id must be null.
	 *
	 * @param array $CannotAccess
	 * @param int $LayerID
	 * @param string $LayerName
	 * @return boolean true on success, false on failure
	 */
	function updateAccessLayer(array $CannotAccess, $LayerID = null, $LayerName = null){
		// if ID is not numeric, we cannot proceed
		if(!is_numeric()){
			throw new FMSException("LayerID must be numeric!");
		}

		// if no restictions are given, we allow access to all applications
		if(count($CannotAccess) < 1){
			$ALString = "*";
		}
		else {
			// generate database string
			$ALString = "";
			foreach ($CannotAccess as $app){
				$ALString .= $app.";";
			}
		}

		// if ID is not given, we create new access layer
		if($LayerID == null){
			if($LayerName == null){
				throw new Exception("LayerName not given.");
			}
			$Statement = "INSERT INTO {$this->MySQL->getPrefix()}access (layer_name, applications) VALUES ($LayerName, '$ALString')";
		}
		// else update existing layer
		else{
			$Statement = $this->MySQL->generateUpdateQuery($this->MySQL->getPrefix()."access", array("applications" => $ALString, "layer_name" => $LayerName), array("id" => $LayerID));
		}

		$this->MySQL->query($Statement);

		return true;
	}
}

?>